/**
 * This Api class lets you define an API endpoint and methods to request
 * data and process it.
 *
 * See the [Backend API Integration](https://docs.infinite.red/ignite-cli/boilerplate/app/services/#backend-api-integration)
 * documentation for more details.
 */
import { ApisauceInstance, create } from "apisauce"

import Config from "@/config"
import { _rootStore } from "@/models/helpers/useStores"

import type { ApiConfig } from "./types"

/**
 * Configuring the apisauce instance.
 */
export const API_CONFIG: ApiConfig = {
  url: Config.BASE_URL,
  timeout: 10000,
}

export const OPENAI_HK_API_CONFIG: ApiConfig = {
  url: Config.OPENAI_HK_API_URL,
  timeout: 30000,
}

/**
 * Initialize the API instance.
 * You can use this function to configure and manage API requests.
 *
 * @param {ApiConfig} config - Optional configuration to override the defaults.
 * @returns {ApisauceInstance} - Configured apisauce instance.
 */

export const createApi = (config: ApiConfig = API_CONFIG): ApisauceInstance => {
  const api = create({
    baseURL: config.url,
    timeout: config.timeout,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
  })

  // 动态添加请求拦截器，确保每次获取最新的 accessToken
  api.addRequestTransform(async (request: any) => {
    const { accessToken } = _rootStore.userStore
    if (accessToken) {
      request.headers["Authorization"] = `Bearer ${accessToken}`
    }
  })

  // 添加响应拦截器
  api.addResponseTransform(async (response: any) => {
    if (!response.ok) {
      // 处理401等未授权的错误

      if (response.status === 401) {
        /*    console.error("Unauthorized, please log in again") */
      }
    } else {
    }
    return response
  })
  return api
}

export const createOpenAIHKApi = (config: ApiConfig = OPENAI_HK_API_CONFIG): ApisauceInstance => {
  return create({
    baseURL: config.url,
    timeout: config.timeout,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Authorization": `Bearer ${Config.OPENAI_HK_API_KEY}`,
    },
  })
}

// Singleton instance of the API for convenience
export const apiSauce = createApi(API_CONFIG)
export const openaiHKAPI = createOpenAIHKApi(OPENAI_HK_API_CONFIG)
